/**
 * 初始化socket连接
 */
import EventBus from "./eventBus";

class Socket {
	socket!: WebSocket | null;
	eventBus!: EventBus;
	constructor(url: string) {
		this.eventBus = new EventBus();
		this.connect(url);
	}
	connect(url: string) {
		this.socket = new WebSocket(url);
		this.socket.onopen = () => {
			console.log("连接成功");
		};
		this.socket.onmessage = (event) => {
			// console.log("收到消息:", event.data);
			this.eventBus.emit("agv:msg", event.data);
		};
		this.socket.onclose = () => {
			console.log("连接关闭");
		};
		this.socket.onerror = (event) => {
			console.error("连接错误:", event);
		};
	}
	disconnect() {
		if (!this.socket) {
			return;
		}
		this.socket.close();
		this.socket.onopen = null;
		this.socket.onmessage = null;
		this.socket.onclose = null;
		this.socket.onerror = null;
		this.socket = null;
		this.eventBus.off("agv:msg");
	}
}

export default Socket;
